import Taro, {Component,Config} from "@tarojs/taro";
import {View, Image, Text} from "@tarojs/components";
import {toJS} from 'mobx'
import {inject, observer} from '@tarojs/mobx'
import {IStoreProps} from '../../store/Stores'
import {getRuntime, servicePhoneNumber, subtime} from '../../utils/common'

import './order_detail.less'
import icon_89 from "../../assets/img/icon_89.png";
import icon_88 from "../../assets/img/icon_88.png";

// 代付款订单详情
interface IHomeProps extends IStoreProps {}

@inject("stores")
@observer
class OrderDetail extends Component<IHomeProps> {
  constructor(props) {
    super(props)
  }

  config: Config = {
    navigationBarTitleText: '订单详情'
  }

  state = {
    id: null,
    info: {}, // 订单详情
    orderDetails: [],
    status: null, // 订单状态
    statusName: '等待付款', // 订单状态名称
    statusDesc: '请尽快完成付款', // 订单状态名称
    isEditAddress: false, // 是否修改地址
  }

  componentWillMount(): void {
    Taro.setNavigationBarTitle({ title:'订单详情' })
    let id = this.$router.params.id
    if(!id) getRuntime().navigateBack()
    this.setState({
      id
    })
    this.getOrder(parseInt(id))
  }

  componentDidShow(): void {
    if(this.state.isEditAddress){
      this.updateUserReceiver()
    }
  }

  handelRouter(url: string = '/pages/index/index'): void {
    getRuntime().navigateTo(url)
  }

  getOrder(id: number) {
    let { PointMallStore } = this.props.stores
    PointMallStore.getOrder({
      formId: id,
      callback: res => {
        this.setState({
          info: toJS(res),
          status: toJS(res.status),
          orderDetails: res.orderDetails[0]
        })
        this.getStatusName(res.status)
      }
    })
  }

  // 取消订单
  cancelOrdedr(id: number) {
    Taro.showModal({
      title: '你确定要取消订单吗?',
      content:'',
      cancelText:'再想想',
      confirmText:'确认取消',
    })
      .then(res => {
        if (res.confirm) {
          let { PointMallStore } =  this.props.stores
          PointMallStore.cancelOrder({
            form: { id },
            callback: () => {
              getRuntime().showToast('取消订单成功~')
              setTimeout( () => {
                getRuntime().navigateTo('/pages/user/order')
              }, 1500)
            }
          })
        }
      });
  }

  // 删除订单
  delOrder() {
    let id = this.state.id
    if(!id) {getRuntime().showToast('参数错误~'); return;}
    Taro.showModal({
      title: '你确定要删除订单吗?',
      content:'',
      cancelText:'再想想',
      confirmText:'确认删除',
    })
      .then(res => {
        if (res.confirm) {
          let { PointMallStore } =  this.props.stores
          PointMallStore.deleteOrder({
            form: { id },
            callback: () => {
              getRuntime().showToast('删除订单成功~')
              setTimeout( () => {
                getRuntime().navigateTo('/pages/user/order')
              }, 1500)
            }
          })
        }
      });
  }

  // 确认收货
  confirmGet(id: number) {
    let { PointMallStore } = this.props.stores
    PointMallStore.confirmGet({
      form: { id },
      callback: () => {getRuntime().showToast('收货成功~')}
    })
  }

  // 再来一单
  againOrder() {
    let info = this.state.info
    if(!info.id) {getRuntime().showToast('参数错误~'); return;}
    let userCart = {
      freight: info.freight,
      itemId: info.id,
      itemNum: info.orderDetails[0]['qty'],
      itemSignPrice: info.orderDetails[0]['price'],
      itemPrice: info.orderDetails[0]['totalPrice'],
      itemSpec: info.orderDetails[0]['spec'],
      name: info.orderDetails[0]['name'],
      picture: info.orderDetails[0]['picture'],
      publicDonations: info.gyMoney,
      pointValue: info.pointValue,
      specNo: '',
      specNoId: info.orderDetails[0]['itemSpecId']
    }
    getRuntime().setStorage('userCart', userCart)
    getRuntime().navigateTo('/pages/mall/order_confirm?id='+info.id)

    /*let { PointMallStore } = this.props.stores
    PointMallStore.placeNewOrder({
      id,
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res,() => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
        })
      }
    })*/
  }

  // 立即支付
  pay() {
    let { id } = this.state
    if(!id) {getRuntime().showToast('参数错误~'); return;}
   /* getRuntime().commonPay(id,5,false, () => {
      getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
    })*/
    let { PointMallStore } = this.props.stores
    PointMallStore.pay({
      form: {
        orderId: id,
        payType: '1',
        isPayPoints: false
      },
      callback: res => {
        // let payParams = JSON.parse(res.payParams)
        getRuntime().wxPay(res,() => {
          getRuntime().navigateTo(`/pages/user/order_pay_success?id=${id}`)
        })
      }
    })
  }

  getStatusName(status: number){
    let statusName = ''
    let statusDesc = ''
    switch (status) {
      case 1: { statusName='等待付款'; statusDesc='(请尽快完成付款)';break;}
      case 2: { statusName='等待商家发货'; statusDesc='(已支付)';break;}
      case 3: { statusName='等待买家收货'; statusDesc='(您的包裹正在配送中...)';break;}
      case 4: { statusName='交易成功'; statusDesc='';break;}
    }
    this.setState({
      statusName,statusDesc
    })
  }

  copy(con: string = '') {
    Taro.setClipboardData({
      data: con
    }).then(() => {
      getRuntime().showToast('复制成功~')
    })
  }

  // 修改地址按钮
  updateAddress() {
    this.setState({
      isEditAddress: true,
    }, () => {
      getRuntime().navigateTo('/pages/mall/address')
    })
  }

  // 更新收货地址
  updateUserReceiver() {
    let { PointMallStore } = this.props.stores
    let orderId = this.state.info.id
    let userSelectAddress = getRuntime().getStorage('userSelectAddress')
    let receiverId = userSelectAddress.id
    PointMallStore.updateUserReceiver({
      form: {
        orderId,
        receiverId
      },
      callback: () => {
        getRuntime().showToast('修改地址成功~')
        this.getOrder(orderId)
      }
    })
  }

  makePhone() {
    getRuntime().makePhoneCall(servicePhoneNumber)
  }

  render() {
    let { info,orderDetails,status,statusName,statusDesc } = this.state
    return (
      <View className='my-order-detail'>
        <View className='order-status'>
           <View className='status'>{statusName}</View>
           <View className='desc'>{statusDesc}</View>
        </View>

        <View className='order-address'>
            <Image className='address-icon' src={icon_88} />
            <View className='info'>
              <View className='list-title'>{info.receiver}  {info.receiverPhone}</View>
              <View className='list-desc'>{info.receiverAddress}</View>
            </View>
          {status===1&& <View className='r' onClick={this.updateAddress.bind(this)}>修改</View>}
        </View>
        <View className='order-spec'>
          <View className='l'>
            <Image className='img' src={orderDetails.picture} />
            <View className='info'>
              <View className='list-title'>{orderDetails.name}</View>
              <View className='list-info'>
                <Text>{orderDetails.spec}</Text>
               {/* <Text className='line'>|</Text>
                <Text>盒装</Text>*/}
              </View>
            </View>
          </View>
          <View className={'r'}>
            <View className='list-price'>
              <Text className='list-small'>￥</Text>{orderDetails.price}</View>
            <View className='list-info' style={{textAlign: 'right'}}>
              <Text>x{orderDetails.qty}</Text>
            </View>
          </View>
        </View>

        <View className='order-item'>
          <View className='line'>
            <View className='name list-desc'>订单金额</View>
            <View className='money'><Text className='list-small'>￥</Text>{info.amount}</View>
          </View>
          <View className='line'>
            <View className='name list-desc'>运费（快递）</View>
            {info.freight>0&&<View className='money'><Text className='list-small'>￥</Text>{info.freight}</View>}
            {info.freight<=0&&<View className='money'><Text>免费配送</Text></View>}
          </View>
          <View className='all-price'>
           应付金额： <Text className='list-small'>￥</Text> {info.actualAmount}
          </View>
        </View>

        <View className='order-item' style={{paddingBottom: '10px'}}>
          <View className='line'>
            <View className='name list-desc'>订单编号</View>
            <View className='money'>{info.orderNo}</View>
          </View>
          <View className='line'>
            <View className='name list-desc'>下单时间</View>
            <View className='money'>{subtime(info.creationTime)}</View>
          </View>
          {info.payTime &&
          <View className='line'>
             <View className='name list-desc'>付款时间</View>
             <View className='money'>{subtime(info.payTime)}</View>
          </View>
          }
          {info.shippingTime &&
          <View className='line'>
             <View className='name list-desc'>发货时间</View>
             <View className='money'>{subtime(info.shippingTime)}</View>
          </View>
          }
          {status===3&&info.shippingNo&&
          <View className='line line2'>
             <View className='name list-desc'>物流快递</View>
             <View className='money company'>
                <Text className='company'>{info.shippingNo}</Text>
                <Text className='btn-copy' onClick={this.copy.bind(this,'189887422570')}>复制</Text>
             </View>
          </View>
          }
          {status!==3&&info.shippingNo&&
          <View className='line'>
             <View className='name list-desc'>物流快递</View>
             <View className='money'>{info.shippingNo}</View>
          </View>
          }
          {info.receiveTime &&
          <View className='line'>
             <View className='name list-desc'>收货时间</View>
             <View className='money'>{subtime(info.receiveTime)}</View>
          </View>
          }
          {info.payTime &&
          <View className='line'>
             <View className='name list-desc'>成交时间</View>
             <View className='money'>{subtime(info.receiveTime)}</View>
          </View>
          }
        </View>

        <View className='contact' onClick={this.makePhone.bind(this)}>
          <Image className='img' src={icon_89} />
          <View className='title'>联系客服</View>
        </View>

        <View className='footer-block' />
        <View className='interval' />

        {status===1&&
        <View className='page-footer2 page-footer3'>
           <View className='list-desc'>应付金额：<Text className='list-small'>￥</Text><Text className='color-orange'>{info.actualAmount}</Text></View>
           <View className='btn' onClick={this.cancelOrdedr.bind(this,info.id)}>取消订单</View>
           <View className='btn btn-active now-pay' onClick={this.pay.bind(this)}>立即付款</View>
        </View>
        }
        {status===3&&
        <View className='page-footer2 page-footer3'>
           <View className='btn btn-active ' onClick={this.confirmGet.bind(this,info.id)}>确认收货</View>
        </View>
        }
        {status===4&&
        <View className='page-footer2 page-footer3'>
           <View className='btn btn-active' onClick={this.againOrder.bind(this)}>再次购买</View>
        </View>
        }
      </View>
    )
  }
}
export default OrderDetail
